﻿/*----------------------------------------------------------
 *  创建者：王建军
 *  创建时间：2018-3-28 16:33:14
 *  功能描述：对象映射
 *  
 *  更新历史：
 ----------------------------------------------------------*/
using Newtonsoft.Json;
using System;

namespace JiamituAPP {
    /// <summary>
    /// 对象映射
    /// </summary>
    public static class MapperHelper {

        /// <summary>
        /// 借助Json系列化解析进行简单的映射
        /// </summary>
        /// <typeparam name="TEntityFrom">源数据</typeparam>
        /// <typeparam name="TEntityTo">目标</typeparam>
        /// <param name="entity">需要转换的数据</param>
        /// <returns>返回转换后的数据</returns>
        public static TEntityTo Mapper<TEntityFrom, TEntityTo>(TEntityFrom entity) {
            string strEntity = JsonConvert.SerializeObject(entity);
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            return JsonConvert.DeserializeObject<TEntityTo>(strEntity, settings);
        }


        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="data">需要反序列化数据</param>
        /// <returns>返回反序列化数据</returns>
        public static T DeserializeObject<T>(String data) {
            return JsonConvert.DeserializeObject<T>(data, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        }

    }
}
